<template>
  <div class="personnelOnDuty" ref="dataListRef">
    <header-com :curTime="curTime" @submit="submit" />
    <div class="dateQuery">
      <div class="left">
        <div>已选择<span style="color: #1890ff">1</span>项</div>
        <div>
          <el-button type="primary" text> 清空 </el-button>
        </div>
      </div>
      <div class="right"><date-steps @changeTime="handleChangeTime" /></div>
    </div>
    <div class="gantt-container">
      <div class="gantt-left">
        <work-station-list
          ref="workStationListRef"
          :headerHeight="headerHeight"
          @scroll="handleScroll_work"
        />
      </div>
      <div class="gantt-center">
        <drag-header
          :unitWidth="step_width"
          :unitNum="stepTime_minute_count"
          :unitTime="stepTime_minute"
          :headerHeight="headerHeight"
          :curTime="curTime"
        />
        <drag-drop
          ref="dragDropRef"
          :unitWidth="step_width"
          :unitNum="stepTime_minute_count"
          :step="step_width / 2"
          :headerHeight="headerHeight"
          @scroll="handleScroll_drag"
        />
      </div>
      <div class="gantt-right">
        <operation
          ref="operationRef"
          :headerHeight="headerHeight"
          @scroll="handleScroll_operation"
        />
      </div>
    </div>
    <custom-menu
      ref="customMenuRef"
      :dataMsg="contextmenuItem"
      :category="contextmenu_category"
      @update="
        () => {
          customMenuRef.$el.style.display = 'none'
        }
      "
    />
  </div>
</template>

<script setup>
import { getCurrentInstance, nextTick, onMounted, ref } from 'vue'
import dragDrop from './dragDrop'
import dragHeader from './dragDrop/dragHeader.vue'
import headerCom from './headerCom'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)
import dateSteps from './components/dateSteps.vue'
import { ElMessage } from 'element-plus'
import workStationList from './workStationList/index.vue'
import operation from './operation.vue'
import customMenu from './customMenu/index.vue'

const vm = getCurrentInstance()
const { $http } = vm.appContext.config.globalProperties

onMounted(() => {
  // 获取第二天日历时间
  // TODO: 如果curTime动态变化，写在watch里
  getCalendarTime_secondDay(
    dayjs(curTime.value).add('1', 'day').format('YYYY-MM-DD')
  )
  nextTick(() => {
    registerContextmenu()
  })
})

let dragDropRef = ref(null)
let operationRef = ref(null)
let workStationListRef = ref(null)
let curTime = ref(dayjs(new Date()).format('YYYY-MM-DD'))
// 步长(一个小时占用的像素宽度)
const step_width = ref(60)
// 步长时间（单位分钟）
const stepTime_minute = 60
// 步长时间数（开始时间 - 结束时间 / 步长时间）
let stepTime_minute_count = ref(0)
// 头部高度
const headerHeight = ref(50)
// 第二天日历时间
let calendarTime = ref('')

// -------------------右击菜单-----------------
let contextmenuItem = ref({})
const customMenuRef = ref(null)
const dataListRef = ref(null)
// 右击类型
let contextmenu_category = ref('')
// 注册右击事件监听
const registerContextmenu = () => {
  dataListRef.value.addEventListener('contextmenu', function (event) {
    let type = event.target.dataset.type
    contextmenuItem.value = event.target.dataset.itemmsg
      ? JSON.parse(event.target.dataset.itemmsg)
      : {}
    console.log('右击菜单数据', contextmenuItem.value)
    if (type !== 'contextmenu') return
    contextmenu_category.value = event.target.dataset.category
    console.log('右击菜单类型', contextmenu_category.value)
    event.preventDefault() // 阻止默认右键菜单
    // 设置菜单的位置
    customMenuRef.value.$el.style.left = event.pageX + 'px'
    customMenuRef.value.$el.style.top = event.pageY + 'px'
    // 显示菜单
    customMenuRef.value.$el.style.display = 'block'
  })
  dataListRef.value.addEventListener('click', function () {
    // 点击页面其他地方时隐藏自定义菜单
    customMenuRef.value.$el.style.display = 'none'
  })
}

// -------------------------------------------

const submit = (val) => {
  console.log('提交', val)
}

const handleChangeTime = (val) => {
  console.log('查询时间变化', val)
}

function calculateStepCount(startTime, endTime, stepDuration) {
  console.log('计算步长', startTime, endTime, stepDuration)
  // 将字符串转换为 dayjs 对象
  const start = dayjs(startTime)
  const end = dayjs(endTime)

  // 计算总时间差（以毫秒为单位）
  const duration = end.diff(start)

  // 计算步长时间（以毫秒为单位）
  const step = dayjs.duration(stepDuration, 'minute').asMilliseconds()

  // 计算步长数量
  const stepCount = Math.ceil(duration / step)
  return [stepCount]
}

const getCalendarTime_secondDay = async (time) => {
  const { data, code, message } = await $http.personnelOnDuty.getCalendarInfo({
    department: 'CNC',
    date: time
  })
  if (code !== 200) {
    ElMessage.error(message)
    return
  }
  console.log('日历信息', data)
  if (!data.exist) {
    // 不存在日历时默认到第二天八点半
    calendarTime.value = dayjs(time)
      .add('9', 'hour')
      .format('YYYY-MM-DD HH:mm:ss')
  } else {
    calendarTime.value = `${data.data[0].calendarDate} ${data.data[0].startTime}`
  }
  // 测试数据
  // calendarTime.value = dayjs(time)
  //   .add('5.5', 'hour')
  //   .format('YYYY-MM-DD HH:mm:ss')
  let [stepCount] = calculateStepCount(
    curTime.value,
    calendarTime.value,
    stepTime_minute
  )
  stepTime_minute_count.value = stepCount
  console.log('多少个30分钟', stepCount)
}

const handleScroll_drag = (top) => {
  console.log('滚动9999', top)
  operationRef.value.setScrollTop(top)
  workStationListRef.value.setScrollTop(top)
}

const handleScroll_work = (top) => {
  operationRef.value.setScrollTop(top)
  dragDropRef.value.setScrollTop(top)
}

const handleScroll_operation = (top) => {
  dragDropRef.value.setScrollTop(top)
  workStationListRef.value.setScrollTop(top)
}
</script>

<style lang="scss" scoped>
.personnelOnDuty {
  height: 100%;
  .dateQuery {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20px;
    .left {
      display: flex;
      align-items: center;
    }
  }
  .gantt-container {
    display: flex;
    margin-top: 5px;
    height: calc(100% - 100px);
    width: 100%;
    .gantt-left {
      width: 350px;
      height: 100%;
    }
    .gantt-center {
      width: calc(100% - 430px);
      height: 100%;
      overflow-x: auto;
    }
    .gantt-right {
      width: 80px;
      height: 100%;
    }
  }
}
::-webkit-scrollbar {
  width: 0px;
  height: 0px;
}
</style>
